import React, { useState,useEffect, useTransition,useRef, Children  } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select, Tabs,Table,Tooltip,List } from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined,SearchOutlined  } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { tslist,testlist,listSubject,listTest,addSubject,editSubject,editTest,addTest,delProject,delTest,delsubjectByTs,deltestByTs} from "@/api/modules/litermark";
import { ProFormColumnsType } from '@ant-design/pro-components'
import { getInfo } from "@/api/login/ssoLogin";

const { TabPane } = Tabs;  
const {Option} = Select
  
const config = () => {  
  const [expandedRowsTab1, setExpandedRowsTab1] = useState([]);  
  const [expandedRowsTab2, setExpandedRowsTab2] = useState([]);  
  const { t } = useTranslation()
  const [tab1Data, setTab1Data] = useState([]);  
  const [tab2Data, setTab2Data] = useState([]);  
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [isModalVisible2, setIsModalVisible2] = useState(false); 
  const [Title2, setTitle2] = useState("")  
  const [form2] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [isView2, SetisView2] = useState(false)
  const [riskdistances,setRiskdistances] = useState([]); 
  const [onReloadNum, setReloadNum] = useState(0); 
  const [onReloadNum2, setReloadNum2] = useState(0); 
  const [peoplelist,setPeople] = useState([])
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 

  // Tab 1的列定义  
const columnsTab1 = [  
  {  
    title: t('config1.subjectLevel1Cn'),  
    dataIndex: 'subjectLevel1Cn',  
    key: 'subjectLevel1Cn',  
  },  
  {  
    title: t('config1.subjectLevel1En'),  
    dataIndex: 'subjectLevel1En',  
    key: 'subjectLevel1En',  
  },  
  {  
    title: t('config1.level1Seq'),  
    dataIndex: 'level1Seq',  
    key: 'level1Seq',  
  },  
]; 

  // Tab 2的列定义  
  const columnsTab2 = [  
    {  
      title: t('config1.testLevel1Cn'),  
      dataIndex: 'testLevel1Cn',  
      key: 'testLevel1Cn',  
    },  
    {  
      title: t('config1.testLevel1En'),  
      dataIndex: 'testLevel1En',  
      key: 'testLevel1En',  
    },  
    {  
      title: t('config1.level1Seq'),  
      dataIndex: 'level1Seq',  
      key: 'level1Seq',  
    },  
  ]; 

  // 使用useEffect在组件挂载时获取数据  
  useEffect(() => {  
    getInfo().then(res=>{
      console.log(res,'res')
      const data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 
    fetchTab1Data(); 
    fetchTab2Data();  
  }, []); // 空数组意味着这个effect只在组件挂载时运行一次  

  const fetchTab1Data = async () => {  

    const { success, data} = await tslist({orderby: '', order: 0})
    if(!success) return false
    let data1 = data.data
    for(let i=0;i<data1.length;i++){
      data1[i].key = i+1
    }
    
    setTab1Data(data1)
  };  


  const fetchTab2Data = async () => {  

    const { success, data} = await testlist({orderby: '', order: 0})
    if(!success) return false
    let data1 = data.data
    data1.map(i=>{
      i.key = i.testLevel1Cn
    })
    setTab2Data(data1)
  };  
 

    // 处理Tab 2的展开与收起  
    const onExpandTab2 = (expanded, record) => {  
      console.log(record.key)
      if (expanded) {  
        setExpandedRowsTab2([...expandedRowsTab2, record.key]);  
      } else {  
        setExpandedRowsTab2(expandedRowsTab2.filter(k => k !== record.key));  
      }  
    };  
  const expandedColumns = [
    {  
      title: t('config1.subjectLevel2Cn'),  
      dataIndex: 'subjectLevel2Cn',  
      key: 'subjectLevel2Cn',  

    },  
    {  
      title: t('config1.subjectLevel2'),  
      dataIndex: 'subjectLevel2',  
      key: 'subjectLevel2',  

    },    
    {  
      title: t('config1.subjectLevel2Cn'),  
      dataIndex: 'subjectLevel2Cn',  
      key: 'subjectLevel2Cn',  
    },  
    {  
      title: t('config1.level2Seq'),  
      dataIndex: 'level2Seq',  
      key: 'level2Seq',  
    },  
    {  
      title: t('config1.calculation'),  
      dataIndex: 'calculation',  
      key: 'calculation',  
    },  
    {  
      title: t('config1.subjectWording'),  
      dataIndex: 'subjectWording',  
      key: 'subjectWording',  
    },  
    {  
      title: t('config1.decisionSeq'),  
      dataIndex: 'decisionSeq',  
      key: 'decisionSeq',  
    },  
    {  
      title: t('config1.operator'),  
      dataIndex: 'operator',  
      key: 'operator',  
    },  
    {  
      title: t('config1.targetValue'),  
      dataIndex: 'targetValue',  
      key: 'targetValue',  
    },  
    {  
      title: t('config1.output'),  
      dataIndex: 'output',  
      key: 'output',  
    },  
    {  
      title: t('config1.outputSeq'),  
      dataIndex: 'outputSeq',  
      key: 'outputSeq',  
    },  
    {  
      title: t('config1.reference'),  
      dataIndex: 'reference',  
      key: 'reference',  
    },  
    {  
      title: t('config1.comment'),  
      dataIndex: 'comment',  
      key: 'comment',  
    },  
    {  
      title: t('config1.remark'),  
      dataIndex: 'remark',  
      key: 'remark',  
    },  
    {  
      title: t('action'),  
      key: 'action',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
          {viewStatus ? null : (
              <>
                  <Button type="link" onClick={() => handleEdit(record)}>  
                  {t('edit')}  
                  </Button>  
                  <Button type="link" danger onClick={() => handleDelete(record.id)}>  
                  {t('delete')}   
                  </Button>   
              </>
            )}
        </>  
      ),  
    }, 
  ]
  // 自定义渲染展开行内容  
  const expandedRowRenderTab1 = (record) => {  
    const columns = [  
      {  
        title: t('config1.subjectLevel2Cn'),  
        dataIndex: 'subjectLevel2Cn',  
        key: 'subjectLevel2Cn',  

      },  
      {  
        title: t('config1.subjectLevel2'),  
        dataIndex: 'subjectLevel2',  
        key: 'subjectLevel2',  

      },    
      {  
        title: t('config1.subjectLevel2Cn'),  
        dataIndex: 'subjectLevel2Cn',  
        key: 'subjectLevel2Cn',  
      },  
      {  
        title: t('config1.level2Seq'),  
        dataIndex: 'level2Seq',  
        key: 'level2Seq',  
      },  
      {  
        title: t('config1.calculation'),  
        dataIndex: 'calculation',  
        key: 'calculation',  
      },  
      {  
        title: t('config1.subjectWording'),  
        dataIndex: 'subjectWording',  
        key: 'subjectWording',  
      },  
      {  
        title: t('config1.decisionSeq'),  
        dataIndex: 'decisionSeq',  
        key: 'decisionSeq',  
      },  
      {  
        title: t('config1.operator'),  
        dataIndex: 'operator',  
        key: 'operator',  
      },  
      {  
        title: t('config1.targetValue'),  
        dataIndex: 'targetValue',  
        key: 'targetValue',  
      },  
      {  
        title: t('config1.output'),  
        dataIndex: 'output',  
        key: 'output',  
      },  
      {  
        title: t('config1.outputSeq'),  
        dataIndex: 'outputSeq',  
        key: 'outputSeq',  
      },  
      {  
        title: t('config1.reference'),  
        dataIndex: 'reference',  
        key: 'reference',  
      },  
      {  
        title: t('config1.comment'),  
        dataIndex: 'comment',  
        key: 'comment',  
      },  
      {  
        title: t('config1.remark'),  
        dataIndex: 'remark',  
        key: 'remark',  
      },  
      {  
        title: t('action'),  
        key: 'action',
        render: (text, record) => (  
          <>  
             <Button type="link"  onClick={() => handleView(record)}>  
             {t('view')}  
            </Button> 
            {viewStatus ? null : (
              <>
                <Button type="link" onClick={() => handleEdit(record)}>  
                  {t('edit')}  
                  </Button>  
                  <Button type="link" danger onClick={() => handleDelete(record.id)}>  
                  {t('delete')}   
                  </Button>  
              </>
            )}
          </>  
        ),  
      },  
    ];  
    return <Table dataSource={record.subData} columns={columns} pagination={false} />;  
  };  

   // 自定义渲染展开行内容  
   const expandedRowRenderTab2 = (record) => {  
    const columns = [  
      {  
        title: t('config1.testLevel2Cn'),  
        dataIndex: 'testLevel2Cn',  
        key: 'testLevel2Cn',  
 
      },  
      {  
        title: t('config1.testLevel2En'),  
        dataIndex: 'testLevel2En',  
        key: 'testLevel2En',  

      },    
      {  
        title: t('config1.level2Seq'),  
        dataIndex: 'level2Seq',  
        key: 'level2Seq',  
      },  
      {  
        title: t('remark'),  
        dataIndex: 'remark',  
        key: 'remark',  
      },  
      {  
        title: t('action'),  
        key: 'action',

        render: (text, record) => (  
          <>  
             <Button type="link"  onClick={() => handleView2(record)}>  
             {t('view')}  
            </Button> 
            {viewStatus ? null : (
              <>
                 <Button type="link" onClick={() => handleEdit2(record)}>  
                  {t('edit')}  
                  </Button>  
                  <Button type="link" danger onClick={() => handleDelete2(record.id)}>  
                  {t('delete')}   
                  </Button>   
              </>
            )}
          </>  
        ),  
      },  
    ];  
    return <Table  dataSource={record.subData} columns={columns} pagination={false} />;  
  };  

  const handleView = (record) =>{
    SetisView(true)
    setTitle("查看/View")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
   }
 
   const handleEdit = (record) =>{
     SetisView(false)
     setTitle("修改/Edit")
     console.log(record,'record')
     form.setFieldsValue({ ...record });  
     setIsModalVisible(true);  
     // 这里可以添加打开模态框并显示编辑表单的逻辑  
   }
 
   const handleDelete = (key) =>{
     let inciIds = []
     inciIds.push(key)
     Modal.confirm({  
       title: 'Confirm Delete',  
       content: 'Please confirm to DELETE SELECTED RECORDS!',  
       onOk() {  
        delsubjectByTs(key,'').then(response=>{
          if(response.data.data == null){
            delsubjectByTs(key,'Y').then(res=>{
              message.success("Success")
              setReloadNum(onReloadNum+1)
              fetchTab1Data()
            })
          }else{
            Modal.confirm({ 
              title: 'Confirm Delete',  
              content: 'Toxicology Endpoints Data has be used,Please confirm to delete', 
              onOk() { 
                delsubjectByTs(key,'Y').then(res=>{
                  message.success("Success")
                  setReloadNum(onReloadNum+1)
                  fetchTab1Data()
                })
               } 
            })
          }
            
         }) 
       },  
     }); 
   }

   const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const handleView2 = (record) =>{
    SetisView2(true)
    setTitle2("查看/View")
    console.log(record,'record')
    form2.setFieldsValue({ ...record });  
    setIsModalVisible2(true);  
   }
 
   const handleEdit2 = (record) =>{
     SetisView2(false)
     setTitle2("修改/Edit")
     console.log(record,'record')
     form2.setFieldsValue({ ...record });  
     setIsModalVisible2(true);  
     // 这里可以添加打开模态框并显示编辑表单的逻辑  
   }
 
   const handleDelete2 = (key) =>{
     let inciIds = []
     inciIds.push(key)
     Modal.confirm({  
       title: 'Confirm Delete',  
       content: 'Please confirm to DELETE SELECTED RECORDS!',  
       onOk() {  
        deltestByTs(key,'').then(response=>{
          if(response.data.data == null){
            deltestByTs(key,'Y').then(res=>{
               message.success("Success")
              setReloadNum2(onReloadNum2+1)
              fetchTab2Data()
            })
          }else{
            Modal.confirm({ 
              title: 'Confirm Delete',  
              content: 'Category Data has be used,Please confirm to delete',  
              onOk() { 
                deltestByTs(key,'Y').then(res=>{
                  message.success("Success")
                 setReloadNum2(onReloadNum2+1)
                 fetchTab2Data()
               })
              }
            })
          }
            
         }) 
       },  
     }); 
   }
   
   const handleCancel2 = () => {  
     setIsModalVisible2(false);  
   };  

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue(); 
    
    if(Title=='修改/Edit'){
      editSubject(values).then(response => {
        message.success("成功")
        setIsModalVisible(false);
        setReloadNum(onReloadNum+1)
        fetchTab1Data()
       });  
      }else{
          addSubject(values).then(response => {
          message.success("成功")
          setIsModalVisible(false);
          setReloadNum(onReloadNum+1)
          fetchTab1Data()
         });
      }

    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleAdd2 = () =>{
    SetisView2(false)
    form2.resetFields()
    setTitle2("新增/New")
    showModal2()
  }

  const showModal2 = () => {  
    setIsModalVisible2(true);  
  };  

  
  const handleOk2 = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form2.getFieldsValue(); 
    if(Title2=='新增/New'){
        //新增
        values.id =null
        addTest(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false);  
            fetchTab2Data()
        }).catch(()=>{
           
        })
    }else{
        //修改
        editTest(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false); 
            fetchTab2Data() 
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  // 定义下拉框的选项  
  const options = [  
      { label: '数字型', value: 'num' },  
      { label: '文字型', value: 'str' },  
    ];  
  const options2 = [  
      { label: 'Yes', value: 'Yes' },  
      { label: 'No', value: 'No' },  
    ]; 

    const expandedRowRender = (record) => {  
      // 如果record有subData属性，则渲染子表格  
      if (record.subData && record.subData.length > 0) {  
        // 使用subData作为子表格的数据源  
        return <Table columns={expandedColumns} dataSource={record.subData} pagination={false} />;  
      }  
      return null; // 如果没有子数据，则不渲染内容  
    };  
    
    // 自定义是否可展开的函数  
    const rowExpandable = (record) => record.name !== 'Not Expandable';  
  return (  
    <div>
    <Card>
    <Tabs type='card'>  
      <TabPane tab={t('config1.ToxicologyEndpoints')} key="1">  
        <Button size='small' disabled={viewStatus} onClick={handleAdd} type="primary" style={{marginBottom:'2%'}}>{t('add')}</Button>  
        <Table  
          dataSource={tab1Data}  
          columns={columnsTab1} 
          expandable={{  
            expandedRowRender,  
            rowExpandable,  
          }}  
        />  
      </TabPane>   
      {/* Tab 2和其他组件可以在这里添加 */}  
      <TabPane tab={t('config1.category')} key="2">  
      <Button size='small' disabled={viewStatus} onClick={handleAdd2} type="primary" style={{marginBottom:'2%'}}>{t('add')}</Button>  
        <Table  
          size='small'
          dataSource={tab2Data}  
          columns={columnsTab2}  
          expandedRowRender={expandedRowRenderTab2}  
          expandedRowKeys={expandedRowsTab2}  
          onExpand={onExpandTab2}  
        />  
      </TabPane> 
    </Tabs>  
    </Card>
    
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              label={t('config1.subjectType')} 
              name="subjectType" 
              rules={[{ required: true, message: '请选择类型！' }]}   
            >  
                <Select disabled={isView}>  
                {options.map((option) => (  
                      <Option key={option.value} value={option.value}>  
                        {option.label}  
                      </Option>  
                    ))}  
                </Select>   
            </Form.Item>  
            <Form.Item  
              name="subjectLevel1Cn"  
              label={t('config1.subjectLevel1Cn')} 
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="subjectLevel1En"  
              label={t('config1.subjectLevel1En')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="level1Seq"  
              label={t('config1.level1Seq')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="subjectLevel2Cn"  
              label={t('config1.subjectLevel2Cn')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="subjectLevel2"  
              label={t('config1.subjectLevel2')} 
              rules={[{ required: true, message: '请输入！' }]}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="level2Seq"  
              label={t('config1.level2Seq')} 
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="calculation"  
              label={t('config1.calculation')}  
              rules={[{ required: true, message: '如没有输N/A！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            {/* <Form.Item  计算公式
              name="dailyAmountMg"  
              label={t('sccs.dailyAmountMg')}  
              rules={[{ required: true, message: '请输入日均使用量(mg/day)' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item>  */}
            <Form.Item  
              name="subjectWording"  
              label={t('config1.subjectWording')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="decisionSeq"  
              label={t('config1.decisionSeq')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="operator"  
              label={t('config1.operator')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="targetValue"  
              label={t('config1.targetValue')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="CalculationFormulaList"  
              label={t('config1.CalculationFormulaList')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="output"  
              label={t('config1.output')}  
            >  
                <Select disabled={isView}>  
                {options2.map((option) => (  
                      <Option key={option.value} value={option.value}>  
                        {option.label}  
                      </Option>  
                    ))}  
                </Select>  
            </Form.Item> 
            <Form.Item  
              name="outputSeq"  
              label={t('config1.outputSeq')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="reference"  
              label={t('config1.reference')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="comment"  
              label={t('config1.comment')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="remark"  
              label={t('config1.remark')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
          </Form>  
        </Modal>  
        <Modal  
          title={Title2}
          visible={isModalVisible2}  
          onOk={handleOk2}  
          onCancel={handleCancel2}  
        >  
          <Form form={form2} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="testLevel1Cn"  
              label={t('config1.testLevel1Cn')} 
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="testLevel1En"  
              label={t('config1.testLevel1En')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="level1Seq"  
              label={t('config1.level1Seq')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="testLevel2Cn"  
              label={t('config1.testLevel2Cn')}  
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="testLevel2En"  
              label={t('config1.testLevel2En')} 
              rules={[{ required: true, message: '请输入！' }]}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="level2Seq"  
              label={t('config1.level2Seq')} 
              rules={[{ required: true, message: '请输入！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="remark"  
              label={t('config1.remark')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
          </Form>  
        </Modal>  
    </div>
  );  
};  
  
export default config;